package com.uduemc.biso.node.web.api.validator.currentsite.impl;

import java.io.IOException;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.uduemc.biso.node.core.entities.SDownload;
import com.uduemc.biso.node.core.entities.SSystem;
import com.uduemc.biso.node.web.api.component.SpringContextUtils;
import com.uduemc.biso.node.web.api.dto.download.DownloadBase;
import com.uduemc.biso.node.web.api.service.DownloadService;
import com.uduemc.biso.node.web.api.service.SystemService;
import com.uduemc.biso.node.web.api.validator.currentsite.CurrentSiteDownloadBase;

public class CurrentSiteDownloadBaseValid implements ConstraintValidator<CurrentSiteDownloadBase, DownloadBase> {

	@Override
	public void initialize(CurrentSiteDownloadBase constraintAnnotation) {

	}

	@Override
	public boolean isValid(DownloadBase base, ConstraintValidatorContext context) {
		long id = base.getId();
		long systemId = base.getSystemId();
		short isShow = base.getIsShow();
		short isTop = base.getIsTop();
		if (isShow < 0 || isShow > 1) {
			return false;
		}
		if (isTop < 0 || isTop > 1) {
			return false;
		}
		if (systemId < 1) {
			return false;
		}
		SystemService systemServiceImpl = SpringContextUtils.getBean("systemServiceImpl", SystemService.class);
		SSystem sSystem = null;
		try {
			sSystem = systemServiceImpl.getInfoById(systemId);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (sSystem == null) {
			context.disableDefaultConstraintViolation();
			context.buildConstraintViolationWithTemplate("系统不存在").addConstraintViolation();
			return false;
		}
		if (id < 1) {
			return true;
		}
		DownloadService downloadServiceImpl = SpringContextUtils.getBean("downloadServiceImpl", DownloadService.class);
		SDownload currentSDownloadInfo = null;
		try {
			currentSDownloadInfo = downloadServiceImpl.getCurrentSDownloadInfo(id);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (currentSDownloadInfo == null) {
			return false;
		}
		return true;
	}

}
